<script setup>
import router from "@/router/index.js";
import {ref} from 'vue'
import {gsap} from "gsap";
import {onMounted} from "vue";
import bind from "@/views/User/components/bindMessage.vue";
import axios from "axios";
import {ElMessage} from "element-plus";


//返回登录页面
const back = () => {
  router.push("/login")
}

// 控制猫移动的动画函数
const catMove = () => {
  gsap.to(".cat", {
    keyframes: {
      x: [0, -20, 200, 0, -100, 800, 0, 0],
      rotate: [0, -20, 60, 0, -40, 60, -450, -360],
    },
    duration: 4,
  });
}

// 组件挂载时的动画效果
onMounted(() => {
  gsap.to(".cat", {
    keyframes: {
      y: [0, -100, 0],
      ease: "bounce.out",
    },
    duration: 4,
  });
})

// 表单数据对象
const ruleForm = ref({
  email: '',
  account: '',
  pass: '',
  checkPass: '',
  code: ''
})

async function register() {
  try {
    let formData = new FormData();
    formData.append("email", ruleForm.value.email);
    formData.append("username", ruleForm.value.account);
    const config = {
      method: 'post',
      url: '/register/bind',
      baseURL: 'http://localhost:8080',
      data: formData
    };
    await axios(config)
        .then((response) => {
          console.log(response)
          if (response.data.code===104003){
            ElMessage({
              type: 'error',
              message: '用户已存在'
            })
          }
          else if (response.data.code===10200) {
            emailShow.value = true
          }
        })
        .catch((error) => {
          console.log(error)
          ElMessage({
            type: 'error',
            message: '用户重复'
          })
        })
  } catch (error) {
    // 打印错误信息
    console.error('Error fetching data:', error);
  }
}


const show = ref(false);
const emailShow = ref(false);
// 表单提交函数
const submitForm = (formEl) => {
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!');
      register()
      console.log(show.value)
    } else {
      console.log('error submit!');
    }
  });
};

const next = () => {
  const formData = new FormData();
  formData.append('email',ruleForm.value.email) ;
  formData.append('username',ruleForm.value.account) ;
  formData.append('password',ruleForm.value.checkPass) ;
  formData.append('code',ruleForm.value.code);
  const config = {
    method: 'post',
    url: '/register/submit',
    baseURL: 'http://localhost:8080',
    headers: {
      'Content-Type': 'application/form-data',
    },
    data: formData
  }
  const res = axios(config)
      .then((response) => {
        if (response.data.code === 10402) {
          ElMessage({
            type: 'warning',
            message: '信息认证失败'
          })
        }
        else if (response.data.code === 10200){
          show.value = true
          console.log(response)
          ElMessage({
            type: 'success',
            message: '注册成功'
          })
        }

      })
      .catch((error) => {
        console.log(error)
        ElMessage({
          type: 'error',
          message: '验证码错误'
        })
      })
}
// 表单引用
const ruleFormRef = ref('');

const validateEmail = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the Email'));

  }
  callback();
}
// 验证账号的函数
const validateAccount = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the account'));
  }
  callback();
}

// 验证密码的函数
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the password'));
  }
  callback();
}

// 验证确认密码的函数
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the password again'));
  } else if (value !== ruleForm.value.pass) {
    callback(new Error("Two inputs don't match!"));
  } else {
    callback();
  }
};

// 表单验证规则
const rules = ref({
  email: [{validator: validateEmail, trigger: 'blur'}],
  account: [{validator: validateAccount, trigger: 'blur'}],
  pass: [{validator: validatePass, trigger: 'blur'}],
  checkPass: [{validator: validatePass2, trigger: 'blur'}],
});
</script>

<template>
  <el-link class="iconfont icon-fanhui" :underline=false @click="back"></el-link>

  <div>
    <div class=" flex flex-column items-center w-96 ml-40">
      <el-link :underline="false"><img src="../../assets/icon/cat.png" alt="img" class="w-96 cat" @click="catMove">
      </el-link>
      <div>要注册嘛~</div>
    </div>
  </div>

  <div>
    <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules" class="w-96 ml-40 mt-20 flex" label-width="auto">
      <div class="w-100">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" autocomplete="off" placeholder="请输入邮箱喵~"/>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="ruleForm.account" autocomplete="off" placeholder="请输入账号喵~"/>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input v-model="ruleForm.pass" type="password" autocomplete="off" placeholder="请输入密码喵~"/>
        </el-form-item>
        <el-form-item label=" " prop="checkPass" class="mb-0">
          <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" placeholder="请再次输入密码，喵~"/>
        </el-form-item>
      </div>

      <div class="ml-8 h-auto flex items-center">
        <el-button class="but shadow" @click="submitForm(ruleFormRef)"> 注册</el-button>
      </div>
    </el-form>
  </div>

  <bind :show="show"></bind>
  <el-dialog v-model="emailShow" title="喵喵确认下这是不是你的邮箱哦~" width="800">
    <el-input v-model="ruleForm.code" placeholder="请输入邮箱验证码"></el-input>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="next()">验证</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.iconfont {
  font-size: 48px;
}

.but {
  height: 50px;
}
</style>